// *****************************************************************************
package horde.internalResources.HorrorControl.HCvis.components;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.RowFilter;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * @author Andres Picazo Cuesta
 */
public class TablePanel extends JPanel {
    /* ---------------------------------------------------------------------- */
    /* GUI elements */

    protected LockedTable tableView;
    protected JLabel filterLabel;
    public JTextField filterField;
//    protected JLabel status;
    protected JTextPane estado;
    protected JScrollPane scrollEstado;
    /* Sorter */
    protected TableRowSorter<TableModel> tableSorter;
    protected TableModel tableModel;
    protected JScrollPane table;
    protected JLayeredPane layeredPane;
    /* Direccion de la imagen de fondo */
    protected String backGroundImg = "";
    protected MouseListener mouseListener;
    // Columna para ordenar
    protected int columna = -1;
    protected JSplitPane split;
    /* ---------------------------------------------------------------------- */

    public TablePanel() {
        createElements();
        organizeElements();
        createMouseListener();
        setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(Color.BLACK),
                BorderFactory.createEmptyBorder(5,5,5,5)));
        tableView.addMouseListener(mouseListener);
        table.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    }
    /* ---------------------------------------------------------------------- */
//    @Override
//    public Insets getInsets() {
//        return new Insets(10,10,10,10);
//    }
    /* ---------------------------------------------------------------------- */

    private void createElements() {
        tableView = new LockedTable();
        table = new JScrollPane(tableView);
        filterLabel = new JLabel(" Filtrar Filas  ");
        //filterLabel.setIcon(new ImageIcon (getClass().getResource("images/s1_search.png")));
        filterLabel.setMinimumSize(new Dimension(100, 30));
        filterField = new JTextField();
        filterField.setMinimumSize(new Dimension(360, 25));
        filterField.addKeyListener(new FilterListener());
        estado = new JTextPane();
        scrollEstado = new JScrollPane(estado);
//        scrollEstado.setPreferredSize(new Dimension(0, 40));
//        scrollEstado.setMinimumSize(new Dimension (0,40));
        estado.setMinimumSize(new Dimension (0,40));
        split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
        split.add (table);
        
//        status = new JLabel("");
//        status.setPreferredSize(new Dimension(0, 20));
//        status.setVerticalAlignment(JLabel.TOP);
//        status.setHorizontalAlignment(JLabel.CENTER);
    }
    /* ---------------------------------------------------------------------- */

    private void organizeElements() {
        setLayout(new BorderLayout(5, 5));
        Box filterBox = Box.createHorizontalBox();
        filterBox.add(filterLabel);
        filterBox.add(filterField);
        filterBox.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        estado.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        add(filterBox, BorderLayout.NORTH);

        add(table, BorderLayout.CENTER);
        add(scrollEstado, BorderLayout.SOUTH);
    }
    /* ---------------------------------------------------------------------- */

    public void createMouseListener() {
        mouseListener = new MouseListener() {

            public void mouseClicked(MouseEvent e) {
                try {
                    int SelectedRow = tableView.getSelectedRow();
                    int SelectedColumn = tableView.getSelectedColumn();
                    /* Si esta filtrado puede que no se seleccione la fila correcta, asi que
                     le digo a la tabla que corrija el valor */
                    SelectedRow = tableView.convertRowIndexToModel(SelectedRow);
                    String element = tableView.getModel().getValueAt(SelectedRow, SelectedColumn).toString();
                    setStatus(element);
                } catch (Exception em) {
                }
            }

            public void mousePressed(MouseEvent e) {
            }

            public void mouseReleased(MouseEvent e) {
            }

            public void mouseEntered(MouseEvent e) {
            }

            public void mouseExited(MouseEvent e) {
            }
        };
    }
    /* ---------------------------------------------------------------------- */

    public Object getElement(int row, int column) {
        return tableView.getModel().getValueAt(row, column);
    }
    /* ---------------------------------------------------------------------- */

    public Object getColumnFromSelectedRow(int column) {
        return getElement(tableView.getSelectedRow(), column);
    }
    /* ---------------------------------------------------------------------- */

    public void setStatus(String text) {
//        status.setText(text);
        estado.setText(text);
    }
    /* ---------------------------------------------------------------------- */

    public LockedTable getTable() {
        return tableView;
    }
    /* ---------------------------------------------------------------------- */

    public TableModel getTableModel() {
        return tableModel;
    }
    /* ---------------------------------------------------------------------- */

    public void setFilterLabelText(String text) {
        filterLabel.setText(text);
    }
    /* ---------------------------------------------------------------------- */

    public void setFilterText(String text) {
        filterField.setText(text);
        this.repaint();
    }
    /* ---------------------------------------------------------------------- */

    public void setTableModel(TableModel model) {
        remove(table);
        remove(split);
        /* ****************************************************************** */
//        backGroundImg = "images/s3_insert.png";
//        layeredPane = new JLayeredPane();
//        JLabel labelImage = new JLabel("EXITO");
//        labelImage.setPreferredSize(new Dimension (200,200));
//        tableView = new LockedTable (model);
//        if (!backGroundImg.equals("")) layeredPane.add(labelImage, new Integer(JLayeredPane.DEFAULT_LAYER-1));
//        layeredPane.add(tableView, JLayeredPane.DEFAULT_LAYER);
//        table = new JScrollPane (layeredPane);
//        table.getViewport().setBackground(Color.WHITE);
        /* ****************************************************************** */
        tableModel = model;
        tableView = new LockedTable(tableModel);
        table = new JScrollPane(tableView);
        table.getViewport().setBackground(Color.WHITE);
        tableSorter = new TableRowSorter<TableModel>(tableView.getModel());
        if (columna != -1) ordenarPorColumna(columna);
        tableView.setRowSorter(tableSorter);
//        add(table, BorderLayout.CENTER);
        split = new JSplitPane (JSplitPane.VERTICAL_SPLIT);
        split.add (table);
        split.add (scrollEstado);
        split.setDividerLocation(600);
        add (split, BorderLayout.CENTER);
//        setStatus ("Elementos: " + tableView.getModel().getRowCount());
        //table.setFont(new Font ("Serif", Font.PLAIN, 18));
        tableView.addMouseListener(mouseListener);
        // -----------------------------------------------------------
        // Esto es un apaño, hay que buscar una forma mejor de hacerlo
        ajustarColumnas(2, Toolkit.getDefaultToolkit().getScreenSize().width);
        // -----------------------------------------------------------

//        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//        tableView.getColumnModel().getColumn(1).setWidth(250);
//        tableView.getColumnModel().getColumn(1).setPreferredWidth(250);
//        setStatus ("Ancho panel: " + this.getPreferredSize().width);
        updateUI();
    }
    /* ---------------------------------------------------------------------- */

    public void useBorder(Color color) {
        setBorder(BorderFactory.createLineBorder(color));
    }
    /* ---------------------------------------------------------------------- */

    public void useBlackBorder() {
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
    }
    /* ---------------------------------------------------------------------- */

    public void useRedBorder() {
        setBorder(BorderFactory.createLineBorder(Color.RED));
    }
    /* ---------------------------------------------------------------------- */

    public void useTestTable() {
        String[] headers = {"Columna 1", "Columna 2"};
        Object[][] data = {{"campo1", "cualquier"}, {"carta", "dato"}, {"corte", "extra"}};
        LockedTable demoTable = new LockedTable(data, headers);
        setTableModel(demoTable.getModel());
    }
    /* ---------------------------------------------------------------------- */
    /* Creo un controlador para el teclado */

    public void updateFilter() {
        if (filterField.getText().length() == 0) {
            tableSorter.setRowFilter(null);
        } else {
            tableSorter.setRowFilter(RowFilter.regexFilter(filterField.getText()));
        }
        updateUI();
    }

    /* ---------------------------------------------------------------------- */
    protected class FilterListener implements KeyListener {

        public void keyTyped(KeyEvent e) {
            updateFilter();
        }

        public void keyReleased(KeyEvent e) {
            updateFilter();
        }

        public void keyPressed(KeyEvent e) {
            updateFilter();
        }

        private void updateFilter() {
            if (filterField.getText().length() == 0) {
                tableSorter.setRowFilter(null);
            } else {
                tableSorter.setRowFilter(RowFilter.regexFilter(filterField.getText()));
            }
            updateUI();
        }
    }
    /* ---------------------------------------------------------------------- */

    /* ---------------------------------------------------------------------- */

    public void setBackGroundImage(String path) {
        backGroundImg = path;
    }
    /* ---------------------------------------------------------------------- */

    public void setDefaultBackgroundImage() throws IOException {
        backGroundImg = "images/tableBackGround.jpg";
    }
    /* ---------------------------------------------------------------------- */

    public void setBlueAndWhite() {
        estado.setBackground(Color.BLUE);
        estado.setForeground(Color.WHITE);
        table.getViewport().setBackground(Color.BLUE);
        table.getViewport().setForeground(Color.WHITE);
        this.setBackground(Color.BLUE);
        this.setForeground(Color.WHITE);
        this.filterLabel.setForeground(Color.WHITE);
    }
    /* ---------------------------------------------------------------------- */

    public void setCurrentFilter(String newFilter) {
        this.filterField.setText(newFilter);
        /* Actualizo el filtro */
        if (filterField.getText().length() == 0) {
            tableSorter.setRowFilter(null);
        } else {
            tableSorter.setRowFilter(RowFilter.regexFilter(filterField.getText()));
        }
        updateUI();
    }
    /* ---------------------------------------------------------------------- */

    public void setVisibleColumns(int numberVisible) {
        if (numberVisible >= 0 && numberVisible < tableView.getModel().getColumnCount()) {
            for (int i = numberVisible; i < tableView.getModel().getColumnCount(); i++) {
                tableView.getColumnModel().getColumn(i).setMaxWidth(0);
                tableView.getColumnModel().getColumn(i).setMinWidth(0);
                tableView.getColumnModel().getColumn(i).setPreferredWidth(0);
            }
            this.tableModel = tableView.getModel();
            this.updateUI();
        }
    }
    /* ---------------------------------------------------------------------- */

    public void ajustarColumnas(int columnaPrincipal, int anchoTotal) {
        try {
            tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            int nCols = tableView.getColumnCount();
            int anchoPrincipal = anchoTotal / 2;
            int anchoSecundario = (anchoTotal - anchoPrincipal) / nCols;
            for (int i = 0; i < nCols; i++) {
                if (i == columnaPrincipal) {
                    tableView.getColumnModel().getColumn(i).setPreferredWidth(anchoPrincipal);
                } else {
                    tableView.getColumnModel().getColumn(i).setPreferredWidth(anchoSecundario);
                }
            }
        } catch (Exception e) {
        }
    }
    /* ---------------------------------------------------------------------- */
    public void setColumnaParaOrdenar (int c) {
        columna = c;
    }
    /* ---------------------------------------------------------------------- */
    private void ordenarPorColumna(int col) {
        List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
        sortKeys.add(new RowSorter.SortKey(col, SortOrder.ASCENDING));
        tableSorter.setSortKeys(sortKeys);
    }
    /* ---------------------------------------------------------------------- */
}
// *****************************************************************************

